import { course } from '../../server/course';
import { file } from '../../server/file';
import { money } from '../../utils/money';

// pages/courseInfo.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: 0,
        name: '',
        price: 0,
        content: [],
        isJoin: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options);
        let courseId = options.course;
        this.getCourseInfo(courseId);

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    returnMainPage() {
        wx.navigateBack({ delta: 1 });
    },
    // 获取课程信息
    getCourseInfo(courseId) {
        course.getCourseInfo(courseId).then(async (res) => {
            let name = res.data.name;
            let price = money.num2yuan(res.data.price);
            console.log(price);
            let imgUrl = await file.downloadPublicFile(res.data.photoId);
            imgUrl = imgUrl.data.url;
            let content = res.data.description.split('\n');
            let isJoin = res.data.isJoin;
            this.setData({ id: courseId, name, price, imgUrl, content, isJoin });
        }).catch((err) => {
            wx.showToast({
                title: '请检查网络连接',
                icon: 'none',
                duration: 1000
            });
        });
    },
    // 报名课程
    joinCourse() {
        let isJoin = this.data.isJoin;
        if (isJoin) {
            wx.showToast({
                title: '您已报名该课程',
                icon: 'none',
                duration: 1000
            });
            return ;
        }
        course.buyCourse(this.data.id).then((res) => {
            if (res.success) {
                wx.showToast({
                    title: '购买课程成功',
                    icon: 'none',
                    duration: 1000
                });
                this.setData({ isJoin: 1 });
            } else {
                wx.showToast({
                    title: '您已报名该课程',
                    icon: 'none',
                    duration: 1000
                });
            }
        }).catch((err) => {
            wx.showToast({
                title: '请检查网路',
                icon: 'none',
                duration: 1000
            });
        });
    }
})